<?php

namespace app\index\service;

use app\common\job\ConsultingLawyerMatchV3;
use app\common\model\Consulting;
use app\common\model\Member;
use app\common\service\SubscriptionMessageService;
use app\index\traits\MatchRecorderTrait;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Queue;

/**
 * 咨询律师匹配 V3
 * 增加SVIP匹配
 * Class ConsultingLawyerMatchV3Service
 * @package app\index\service
 */
class ConsultingLawyerMatchV3Service
{
    use MatchRecorderTrait;

    /**
     * 进入下一阶段
     * @param $data
     * @return void
     */
    public function next($data)
    {
        $id = $data['id'];
        $step = $data['step'];

        $consulting = Consulting::where('id', $id)->find();

        if (is_id($consulting->lawyerId)) {
            return;
        }

        // 2023-11-20 周三让改成只匹配一个SVIP，不匹配第二个了
        // if ($step == 2) {
        //     $this->matchSvip2($consulting);
        // }
        //
        // if ($step == 3) {
        // }

        $this->matchSvip3($consulting);
    }

    /**
     * 匹配第一个SVIP
     * @param Consulting $consulting
     * @return void
     */
    public function matchSvip(Consulting $consulting)
    {
        if (is_id($consulting->lawyerId)) {
            return;
        }

        $initMatchType = $consulting->initMatchType;
        $provinceId = $consulting->provinceId;

        // 获取SVIP
        $lawyerId = $this->getSvip($provinceId);

        if (is_id($lawyerId)) {
            // 记录匹配情况
            $this->recordMatch($lawyerId, $consulting->id, Consulting::MATCH_TYPE_SVIP);

            // SVIP 匹配第二个律师的延时（相对第1个律师匹配时间）
            $expTime = Config::get('consulting.svip_lawyer_time', 2 * 60);

            // 设置律师（发公众号消息）
            $pagepath = 'pages/lawyer/lawyer?rush_id=' . $consulting->id;
            $userName = Member::where('id', $consulting->memberId)->value('nickname');
            $this->getSubscriptionMessageService()->messageFreeConsulting($lawyerId, $userName, $consulting->ask, time(), $expTime, $pagepath);

            // 设置任务 2分钟后触发第3阶段(去掉了2阶段)
            $job_data = ['id' => $consulting->id, 'step' => 3];
            Queue::later($expTime, ConsultingLawyerMatchV3::class, $job_data);

        } else {

            // 直接进入3阶段
            $this->matchSvip3($consulting);
        }

    }

    /**
     * 匹配第2个SVIP
     * @param Consulting $consulting
     * @return void
     */
    private function matchSvip2(Consulting $consulting)
    {
        $provinceId = $consulting->provinceId;

        // 获取SVIP
        $lawyerId = $this->getSvip($provinceId);

        if (is_id($lawyerId)) {
            // 记录匹配情况
            $this->recordMatch($lawyerId, $consulting->id, Consulting::MATCH_TYPE_SVIP);

            // 超时的延时（相对第2个律师匹配时间）
            $expTime = Config::get('consulting.svip_open_time', 2 * 60);

            // 设置律师（发公众号消息）
            $pagepath = 'pages/lawyer/lawyer?rush_id=' . $consulting->id;
            $userName = Member::where('id', $consulting->memberId)->value('nickname');
            $this->getSubscriptionMessageService()->messageFreeConsulting($lawyerId, $userName, $consulting->ask, time(), $expTime, $pagepath);

            // 设置任务 3分钟后触发第3阶段
            $job_data = ['id' => $consulting->id, 'step' => 3];
            Queue::later($expTime, ConsultingLawyerMatchV3::class, $job_data);

        } else {

            $this->matchSvip3($consulting);
        }

    }

    /**
     * 开放给普通律师
     * @param Consulting $consulting
     * @return void
     */
    private function matchSvip3(Consulting $consulting)
    {

        $initMatchType = $consulting->initMatchType;

        // 原匹配方式是随机匹配
        if ($initMatchType == Consulting::MATCH_TYPE_RANDOM) {
            $this->getConsultingLawyerMatchV2Service()->matchRandom0($consulting);
        }

        // 原匹配方式是抢单
        if ($initMatchType == Consulting::MATCH_TYPE_RUSH) {
            $this->getConsultingLawyerMatchService()->backToPool($consulting);
        }
    }


    private function getSvip($provinceId)
    {
        if (!is_id($provinceId)) {
            return null;
        }

        $key = 'svip:' . $provinceId;

        // 查询该省份配置， 轮次
        $round = Cache::get($key, 'A');

        $record = $this->getSvipByRound($provinceId, $round);

        if (is_null($record)) {
            $round = $this->getNextRound($round);
            $record = $this->getSvipByRound($provinceId, $round);
            if (!$record) {
                // 两轮都没有
                return null;
            }

            // 切换轮次
            Cache::set($key, $round);
        }

        return $record->id;
    }

    private function getSvipByRound($provinceId, $round)
    {
        $tableName = Member::getTable();
        $record = Member::leftJoin('member_svip_province_rel mspr', "$tableName.id=mspr.memberId")
                        ->where("$tableName.type", '1')
                        ->where("$tableName.subType", '0')
                        ->where("$tableName.status", '1')
                        ->where("mspr.provinceId", $provinceId)
                        ->where("mspr.round", $round)
                        ->tableField(['id',], $tableName)
                        ->find();

        // 律师切换轮次
        if ($record) {
            $record->svipProvinces()->attach($provinceId, ['round' => $this->getNextRound($round)]);
        }

        return $record;
    }

    private function getNextRound(string $round): string
    {
        return $round === 'A' ? 'B' : 'A';
    }

    private function getConsultingLawyerMatchService(): ConsultingLawyerMatchService
    {
        return app(ConsultingLawyerMatchService::class);
    }

    private function getConsultingLawyerMatchV2Service(): ConsultingLawyerMatchV2Service
    {
        return app(ConsultingLawyerMatchV2Service::class);
    }

    private function getSubscriptionMessageService(): SubscriptionMessageService
    {
        return app(SubscriptionMessageService::class);
    }

}
